package team.pwy.controller;

import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Tuple;
import team.pwy.GameLeaderboard;
import team.pwy.consts.RbmConsts;
import team.pwy.pojo.dto.CollectDTO;
import team.pwy.pojo.entity.*;
import team.pwy.service.*;
import team.pwy.vo.Result;
import team.pwy.vo.TypeDTO;

import java.util.*;

@RestController
@RequestMapping("movie")
public class MovieController {

    @Resource
    private MovieService movieService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private SessionService sessionService;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Resource
    private ImgService imgService;

    // 首页正在热映
    @GetMapping()
    public Result findHotting(Integer status, Integer pageNum, Integer pageSize) {
        PageInfo<Movie> hotting = movieService.findHotting(status, pageNum, pageSize);
        return new Result("200", "查询成功", hotting);
    }

    // 首页今日票房
    @GetMapping("/sorce")
    public Result findTopFive() {
        GameLeaderboard leaderboard = new GameLeaderboard();
        Set<Tuple> topPlayers = leaderboard.getTopPlayers(5);

        List<Movie> movieList = new ArrayList<>();
        for (Tuple tuple : topPlayers) {
            Movie movie = new Movie();

            String[] movieString = tuple.getElement().split("&");
            movie.setId(Integer.valueOf(movieString[0]));
            movie.setTitle(movieString[1]);
            movie.setPosterImg(movieString[2]);
            movie.setGrossed(tuple.getScore());
            movieList.add(movie);
        }

        return new Result("200", "查询成功", movieList);
    }

    // 电影详细页根据id获取
    @GetMapping("/findById")
    public Result findById(Integer id) {
        Movie ids = movieService.findById(id);
        return new Result("200", "查询成功", ids);
    }

    @GetMapping("/findByTime")
    public Result findById() {
        List<Movie> time = movieService.findByTime();
        return new Result("200", "查询成功", time);
    }

    @GetMapping("/findByScore")
    public Result findByScore() {
        List<Movie> time = movieService.findByScore();
        return new Result("200", "查询成功", time);
    }

    @GetMapping("/findByHot")
    public Result findByHot() {
        List<Movie> time = movieService.findByHot();
        return new Result("200", "查询成功", time);
    }

    // 场次页面根据movieid查询
    @GetMapping("findById/{id}")
    public Result findByMovieId(@PathVariable("id") Integer id) {
        Movie ids = movieService.findById(id);
        return new Result("200", "查询成功", ids);
    }

    // 根据id去查演员
    @GetMapping("findByPerformerId/{id}")
    public Result findByPerformerId(@PathVariable("id") Integer id) {
        List<Performer> performers = imgService.findByperformer(id);
        return new Result("200", "查询成功", performers);
    }

    @GetMapping("findByType/{type}")
    public Result findByType(@PathVariable("type") String type) {
        List<Movie> movies = movieService.findByType(type);
        return new Result("200", "查询成功", movies);
    }

    @GetMapping("/findActive")
    public Result findByActive() {
        List<Movie> movies = movieService.findByActive();
        return new Result("200", "查询成功", movies);
    }

    @GetMapping("/findBytypes")
    public Result findByTypes(TypeDTO typeDTO, Integer pageNum, Integer pageSize) {
        PageInfo<Movie> movies = movieService.findByTypes(typeDTO, pageNum, pageSize);
        return new Result("200", "查询成功", movies);
    }

    @GetMapping("/desire")
    public Result findByDesire() {
        List<Movie> expect = movieService.findByDesire();
        return new Result("200", "根据想看查询成功", expect);
    }
    //添加我的收藏

    @PostMapping("{ids}/{userId}")
    public Result addCollect(@PathVariable("ids") Integer id, @PathVariable("userId") Integer userId) {
        ListOperations collectList = redisTemplate.opsForList();
        List cList = collectList.range("userId" + userId, 0, -1);
        if (cList.contains(id)) {
            if (collectList.remove("userId" + userId, 1, id) == 1) {

                Map<String, Integer> maps = new HashMap<>();

                maps.put("status", 0);//取消收藏
                maps.put("userId", userId);
                maps.put("movieId", id);
                rabbitTemplate.convertAndSend(RbmConsts.SEC_QUEUE_COLLECT, maps);
                return new Result("200", "移除收藏");
            } else {
                return new Result("400", "失败");
            }
        } else {
            collectList.leftPush("userId" + userId, id);
            Map<String, Integer> maps = new HashMap<>();

            maps.put("status", 1);//1添加收藏
            maps.put("userId", userId);
            maps.put("movieId", id);
            rabbitTemplate.convertAndSend(RbmConsts.SEC_QUEUE_COLLECT, maps);
            return new Result("200", "添加");
        }
    }

    @PostMapping("{ids}/{userId}/{value}")
    public Result addScore(@PathVariable("ids") Integer id, @PathVariable("userId") Integer userId, @PathVariable("value") Double grade) {
        ListOperations gradeList = redisTemplate.opsForList();
        List cList = gradeList.range("scoreId" + userId, 0, -1);
        if (cList.contains(id)) {
            if (gradeList.remove("scoreId" + userId, 1, id) == 1) {
                Map<String, Object> maps = new HashMap<>();

                maps.put("status", 0);//0取消评分
                maps.put("userId", userId);
                maps.put("movieId", id);
                rabbitTemplate.convertAndSend(RbmConsts.SCORE_QUEUE, maps);
                return new Result("200", "移除评分");
            } else {
                return new Result("400", "失败");
            }
        } else {
            gradeList.leftPush("scoreId" + userId, id);
            Map<String, Object> maps = new HashMap<>();
            maps.put("status", 1);//1添加评分
            maps.put("userId", userId);
            maps.put("movieId", id);
            maps.put("grade", grade);
            rabbitTemplate.convertAndSend(RbmConsts.SCORE_QUEUE, maps);
            return new Result("200", "添加");
        }

    }

    @GetMapping("/isScore/{ids}/{userId}")
    public Result isScore(@PathVariable("ids") Integer id, @PathVariable("userId") Integer userId) {
        List cList = redisTemplate.opsForList().range("scoreId" + userId, 0, -1);
        if (cList.contains(id)) {
            return new Result("500", "已经存在");
        } else {
            return new Result("200", "不存在");
        }
    }

    @GetMapping("/isCollect/{ids}/{userId}")
    public Result isCollect(@PathVariable("ids") Integer id, @PathVariable("userId") Integer userId) {
        List cList = redisTemplate.opsForList().range("userId" + userId, 0, -1);
        if (cList.contains(id)) {
            return new Result("500", "已经存在");
        } else {
            return new Result("200", "不存在");
        }
    }

    //删除我的收藏
    @GetMapping("/delCollect")
    public Result delCollect(Integer id, Integer userId) {
        movieService.delCollect(id, userId);
        return new Result("200", "删除收藏成功!");
    }

    //查询我的收藏
    @GetMapping("/lookCollect")
    public Result lookCollect(Integer userId, Integer pageNum, Integer pageSize) {
        List<Collect> collects = movieService.lookCollect(userId, pageNum, pageSize);

        List<CollectDTO> collectDTOS = new ArrayList<>();

        if (collects != null && !collects.isEmpty()) {
            for (Collect collect : collects) {
                CollectDTO collectDTO = new CollectDTO();
                Movie movie = movieService.findById(collect.getMovieId());
                collectDTO.setId(collect.getId());
                collectDTO.setUserId(collect.getUserId());
                collectDTO.setMovieId(collect.getMovieId());
                collectDTO.setMovieTitle(collect.getMovieTitle());
                collectDTO.setPosterImg(collect.getPosterImg());
                collectDTO.setMoviePrice(collect.getMoviePrice());
                collectDTO.setStatus(collect.getStatus());
                List<Session> sessionList = sessionService.findByMovieIdDesc(movie.getId());
                if (sessionList != null && !sessionList.isEmpty()) {
                    collectDTO.setStartTime(sessionList.get(0).getStarTime());
                }
                collectDTO.setLanguage(movie.getLanguage());
                collectDTO.setScore(movie.getScore());
                collectDTO.setDirector(movie.getDirector());
                collectDTOS.add(collectDTO);
            }
        }

        return new Result("200", "查询收藏成功", new PageInfo<>(collectDTOS));
    }

    @GetMapping("/lookHistory")
    public Result lookHistory(Integer userId, Integer pageNum, Integer pageSize) {
        PageInfo<PwyViewingHistory> histories = movieService.lookHistory(userId, pageNum, pageSize);

        return new Result("200", "查询观影历史成功", histories);
    }

    @GetMapping("/findByStatus/{status}")
    public Result findByStatus(@PathVariable("status") Integer status) {
        List<Movie> movieList = movieService.findByStatus(status);
        return new Result("200", "查询成功", movieList);
    }


}
